package com.hhu.webdemo;


import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

public class TWebHandler extends Handler {
    public final  static  String TAG = "TWebHandler";

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if( msg.what == 2000){
            String jsCode = msg.obj.toString();
            callJs(jsCode);
        }
    }

    WebView webView ;
    public  TWebHandler( WebView _webView){
        this.webView = _webView;
        this.init();
    }

    void  init(){
        try{
            webView.getSettings().setJavaScriptEnabled(true);
            webView.addJavascriptInterface(this, "hhuiot");
        }
        catch (Exception er){
            Log.e(TAG, "init: ", er);
        }
    }

    @JavascriptInterface
    public void jsCallJava(String action ,  String data){
        Message msg = new Message();
        msg.what = 1000;
        TCallData callData = new TCallData();
        callData.action = action;
        callData.data = data;
        msg.obj = callData;
        this.sendMessage(msg);
    }
    public void javaCallJs(String jsCode){
        Message msg = new Message();
        msg.what = 2000;
        msg.obj = jsCode;
        sendMessage(msg);
    }

    void callJs(String jsCode){
        try{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                webView.evaluateJavascript(jsCode, null);
            } else {
                webView.loadUrl(jsCode);
            }
        }
        catch (Exception er){
            Log.e(TAG, "callJs: ",er );
        }
    }



    public static  class  TCallData{

        public String action = "";
        public String data = "";
    }
}
